import { NextRequest, NextResponse } from 'next/server';
import { Img2ImgRequest, SDSuccessResponse, SDErrorResponse } from '@/types/base';
import { SD_BASE_URL } from '@/lib/config';
import { getDb } from '@/lib/db';
import { checkPromptSensitiveWords } from '@/utils/sensitiveWordCheck';

export async function POST(request: NextRequest) {
  try {
    // 获取请求体数据
    const body = await request.json() as Img2ImgRequest;
    
    // 敏感词检查
    const sensitiveCheck = checkPromptSensitiveWords(body.prompt, body.negative_prompt);
    if (sensitiveCheck.hasSensitive) {
      return NextResponse.json(sensitiveCheck.error, { status: 400 });
    }
    
    // 构造转发到目标API的数据对象
    const forwardData: Img2ImgRequest = {
      init_images: body.init_images || [],
      prompt: body.prompt || "",
      negative_prompt: body.negative_prompt || "",
      denoising_strength: body.denoising_strength !== undefined ? body.denoising_strength : 0.75,
      sampler_name: body.sampler_name || "Euler",
      batch_size: body.batch_size || 1,
      n_iter: body.n_iter || 1,
      steps: body.steps || 50,
      cfg_scale: body.cfg_scale || 7,
      width: body.width || 512,
      height: body.height || 512
    };

    // 添加可选参数（如果存在）
    if (body.styles !== undefined) forwardData.styles = body.styles;
    if (body.seed !== undefined) forwardData.seed = body.seed;
    if (body.subseed !== undefined) forwardData.subseed = body.subseed;
    if (body.subseed_strength !== undefined) forwardData.subseed_strength = body.subseed_strength;
    if (body.seed_resize_from_h !== undefined) forwardData.seed_resize_from_h = body.seed_resize_from_h;
    if (body.seed_resize_from_w !== undefined) forwardData.seed_resize_from_w = body.seed_resize_from_w;
    if (body.scheduler !== undefined) forwardData.scheduler = body.scheduler;
    if (body.restore_faces !== undefined) forwardData.restore_faces = body.restore_faces;
    if (body.tiling !== undefined) forwardData.tiling = body.tiling;
    if (body.do_not_save_samples !== undefined) forwardData.do_not_save_samples = body.do_not_save_samples;
    if (body.do_not_save_grid !== undefined) forwardData.do_not_save_grid = body.do_not_save_grid;
    if (body.eta !== undefined) forwardData.eta = body.eta;
    if (body.s_min_uncond !== undefined) forwardData.s_min_uncond = body.s_min_uncond;
    if (body.s_churn !== undefined) forwardData.s_churn = body.s_churn;
    if (body.s_tmin !== undefined) forwardData.s_tmin = body.s_tmin;
    if (body.s_tmax !== undefined) forwardData.s_tmax = body.s_tmax;
    if (body.s_noise !== undefined) forwardData.s_noise = body.s_noise;
    if (body.override_settings !== undefined) forwardData.override_settings = body.override_settings;
    if (body.override_settings_restore_afterwards !== undefined) forwardData.override_settings_restore_afterwards = body.override_settings_restore_afterwards;
    if (body.refiner_checkpoint !== undefined) forwardData.refiner_checkpoint = body.refiner_checkpoint;
    if (body.refiner_switch_at !== undefined) forwardData.refiner_switch_at = body.refiner_switch_at;
    if (body.disable_extra_networks !== undefined) forwardData.disable_extra_networks = body.disable_extra_networks;
    if (body.firstpass_image !== undefined) forwardData.firstpass_image = body.firstpass_image;
    if (body.comments !== undefined) forwardData.comments = body.comments;
    if (body.resize_mode !== undefined) forwardData.resize_mode = body.resize_mode;
    if (body.image_cfg_scale !== undefined) forwardData.image_cfg_scale = body.image_cfg_scale;
    if (body.mask !== undefined) forwardData.mask = body.mask;
    if (body.mask_blur !== undefined) forwardData.mask_blur = body.mask_blur;
    if (body.mask_blur_x !== undefined) forwardData.mask_blur_x = body.mask_blur_x;
    if (body.mask_blur_y !== undefined) forwardData.mask_blur_y = body.mask_blur_y;
    if (body.mask_round !== undefined) forwardData.mask_round = body.mask_round;
    if (body.inpainting_fill !== undefined) forwardData.inpainting_fill = body.inpainting_fill;
    if (body.inpaint_full_res !== undefined) forwardData.inpaint_full_res = body.inpaint_full_res;
    if (body.inpaint_full_res_padding !== undefined) forwardData.inpaint_full_res_padding = body.inpaint_full_res_padding;
    if (body.inpainting_mask_invert !== undefined) forwardData.inpainting_mask_invert = body.inpainting_mask_invert;
    if (body.initial_noise_multiplier !== undefined) forwardData.initial_noise_multiplier = body.initial_noise_multiplier;
    if (body.latent_mask !== undefined) forwardData.latent_mask = body.latent_mask;
    if (body.force_task_id !== undefined) forwardData.force_task_id = body.force_task_id;
    if (body.sampler_index !== undefined) forwardData.sampler_index = body.sampler_index;
    if (body.include_init_images !== undefined) forwardData.include_init_images = body.include_init_images;
    if (body.script_name !== undefined) forwardData.script_name = body.script_name;
    if (body.script_args !== undefined) forwardData.script_args = body.script_args;
    if (body.alwayson_scripts !== undefined) forwardData.alwayson_scripts = body.alwayson_scripts;
    if (body.send_images !== undefined) forwardData.send_images = body.send_images;
    if (body.save_images !== undefined) forwardData.save_images = body.save_images;
    if (body.infotext !== undefined) forwardData.infotext = body.infotext;

    // 转发请求到目标API
    const response = await fetch(`${SD_BASE_URL}/sdapi/v1/img2img`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(forwardData)
    });

    // 检查响应状态
    if (!response.ok) {
      const detail = await response.text();
      return NextResponse.json(
        { error: 'Request error', detail, status: response.status },
        { status: response.status }
      );
    }

    // 返回目标API的响应
  const data: SDSuccessResponse = await response.json();

  // 入库：记录提交的请求与返回内容（注意：包含 base64 图片，可能较大）
  try {
    const db = await getDb();
    await db.create('img2img_records', {
      type: 'img2img',
      createdAt: new Date().toISOString(),
      request: body,        // 原始请求（含 init_images 等）
      forwarded: forwardData, // 实际转发到 SD 的参数
      response: data        // SD 返回数据（含 images/base64）
    } as any);
  } catch (persistErr) {
    console.error('保存 img2img 记录失败:', persistErr);
  }

  return new Response(JSON.stringify(data), {
    status: 200,
  });

  } catch (error: any) {
    // 处理和返回错误
    const errorResponse: SDErrorResponse = { 
      error: 'Internal Server Error', 
      detail: error.message || 'Unknown error occurred' 
    };
    
    return new Response(JSON.stringify(errorResponse), { 
      status: 500,
    });
  }
}